package com.abc.controller;

import com.abc.annotation.PermInfo;
import com.abc.dao.UploadMapper;
import com.abc.entity.SysUser;
import com.abc.entity.Upload;
import com.abc.service.UploadService;
import com.abc.util.PageUtils;
import com.abc.util.StringUtils;
import com.abc.vo.Json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@PermInfo(value = "上传模块", pval = "a:upload")
@RequestMapping("/api/v1/upload")
@RestController
public class UploadController {

    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    UploadService uploadService;

    @Autowired
    UploadMapper uploadMapper;

    @PermInfo("查询文件列表")
    @RequiresPermissions("a:upload:query")
    @RequestMapping("/query")
    public Json query(@RequestBody String body) {
        String oper = "query upload";
        log.info("{}, body: {}", oper, body);
        JSONObject json = JSON.parseObject(body);
        String nick = json.getString("nick");
        Page<Upload> page = uploadService.queryUploadListPage(PageUtils.getPageParam(json), Upload.Build().build());
        return Json.succ(oper).data("page", page);
    }


    @Value("${my.upload-path}")
    private String uploadPath;

    @PermInfo("上传文件")
    @RequiresPermissions("a:upload:add")
    @PostMapping("/add")
    public Json add(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @RequestParam("fileName") String fileName) {
        String oper = "file upload";
        log.info("{}, filename: {} ,name: {}", oper, file.getOriginalFilename(), name);
        if (file.isEmpty()) {
            return Json.fail("上传失败");
        }
        String originalFilename = "";
        if (file.getOriginalFilename().equals("blob")) {
            originalFilename = fileName;
        } else {
            file.getOriginalFilename();
        }

        Upload upload;
        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();


            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("YYYY/MM/dd/");
            String dateStr = formatter2.format(LocalDate.now());
            String mainPath = dateStr + StringUtils.getRandomString(6) + suffixName;
            Path savePath = Paths.get(uploadPath + mainPath);
            Path downPath = Paths.get("/upload/" + mainPath);
            File nfile = savePath.toFile();
            if (!nfile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                System.out.println("目标文件所在目录不存在，准备创建它！");
                if (!nfile.getParentFile().mkdirs()) {
                    System.out.println("创建目标文件所在目录失败！");
                }
            }
            Files.write(savePath, bytes);

            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            upload = Upload.Build().name(name).userId(user.getUid()).path(downPath.toString().replaceAll("\\\\", "/")).size(Long.toString(file.getSize())).suffix(suffixName).createTime(LocalDateTime.now()).build();
            uploadMapper.insertUpload(upload);
        } catch (IOException e) {
            return Json.fail("上传失败");
        }
        return Json.succ(oper).data(upload);

    }

    @PermInfo("删除文件")
    @RequiresPermissions("a:upload:del")
    @PostMapping("/del")
    public Json del(@RequestBody String body) {
        String oper = "del upload";
        log.info("{}, body: {}", oper, body);
        Upload upload = JSON.parseObject(body, Upload.class);
        List<Upload> sUpload = uploadMapper.queryUpload(Upload.Build().id(upload.getId()).build());
        if (!sUpload.isEmpty()) {
            File file = new File(sUpload.get(0).getPath());
            file.delete();
            uploadMapper.deleteById(sUpload.get(0).getId());
        }
        return Json.succ("删除成功");
    }


    @PermInfo("获取图片列表")
    @RequiresPermissions("a:upload:imageList")
    @RequestMapping("/imageList")
    public Json getImageList(@RequestBody String body) {
        String oper = "imageList upload";
        log.info("{}, body: {}", oper, body);
        JSONObject json = JSON.parseObject(body);
        Page<Upload> page = uploadService.selectImageListPage(PageUtils.getPageParam(json));
        return Json.succ(oper, "page", page);
    }

}
